import React, { useEffect, useState, memo, useRef } from 'react';

import {
  Table,
  Modal,
  Form,
  Input,
  InputNumber,
  DatePicker,
  Space,
  Popconfirm
} from 'antd';
import http from '@/services/request';
import { ProToolBar } from '@/base-ui';
import { IToolButton } from '@/base-ui/tool-bar';
import planPicture from '@/assets/img/chicken_ill.jpeg';
import DivWrapper from './style';

import { FormColumns } from './config';
import TipsHeader from '@/components/TipsHeader';

const NewForm = (props: any) => {
  return (
    <Form ref={props.newref} form={props.form} layout={'vertical'}>
      <Form.Item label="疫病名称" name="diseaseName">
        <Input />
      </Form.Item>
      <Form.Item label="主要症状" name="mainSymptom">
        <Input />
      </Form.Item>
      <Form.Item label="得病鸡舍数" name="illnessHenhouseNumber">
        <InputNumber min={1} defaultValue={1} />
      </Form.Item>
      <Form.Item name="illnessChickenTotal" label="疫病总数量">
        <InputNumber min={1} defaultValue={1} />
      </Form.Item>
      <Form.Item name="deathTotal" label="死亡总数量">
        <InputNumber min={0} defaultValue={1} />
      </Form.Item>
      <Form.Item label="得病时间" name="illnessDate">
        <DatePicker />
      </Form.Item>
      <Form.Item label="结束时间" name="recoveryDate">
        <DatePicker />
      </Form.Item>
      <Form.Item label="治疗方案" name="treatmentPlan">
        <Input />
      </Form.Item>
      <Form.Item label="方案结果" name="planResult">
        <Input />
      </Form.Item>
    </Form>
  );
};

const GetUseManage = memo(() => {
  const [dataSource, setdataSource]: any = useState([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [edited, setEdited]: any = useState('');
  const newref: any = useRef();
  const [form] = Form.useForm();
  const buttonGroup: IToolButton[] = [
    {
      type: 'create',
      text: '新增记录',
      isShow: true,
      onClick: () => {
        setAddModalVisible(true);
      },
      id: 9
    }
  ];
  const FormColumsArray = [
    ...FormColumns,
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record) => (
        <Space>
          <a onClick={() => openEditModal(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            onConfirm={() => deleteItem(record.id)}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
        </Space>
      ),
      fixed: 'right'
    }
  ];
  useEffect(() => {
    http.get('/feed/diseaseSummaryFarming/list/1/10').then((res) => {
      setdataSource(res.data?.records);
    });
  }, []);

  const deleteItem = (id) => {
    http.delete(`/feed/diseaseSummaryFarming/delete/${id}`).then(() => {
      http.get('/feed/diseaseSummaryFarming/list/1/30').then((res) => {
        setdataSource(res.data.records);
      });
    });
  };

  const openEditModal = (item) => {
    setEdited(item);
    setAddModalVisible(true);
    const { illnessDate, recoveryDate, ...rest } = item;
    form.setFieldsValue(rest);
  };

  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    // 修改操作
    if (edited) {
      const newedited = newref.current.getFieldsValue();
      newedited.illnessDate &&
        (newedited.illnessDate = newedited.illnessDate.toJSON());
      newedited.recoveryDate &&
        (newedited.illnessDate = newedited.recoveryDate.toJSON());
      http
        .put(`/feed/diseaseSummaryFarming/update`, {
          id: edited.id,
          ...newedited
        })
        .then(() => {
          http.get('/feed/diseaseSummaryFarming/list/1/30').then((res) => {
            setdataSource(res.data.records);
          });
        });
      setEdited(null);
      form.resetFields();
      return;
    }

    //id不在--就是新增
    const addData = newref.current.getFieldsValue();
    addData.illnessDate && (addData.illnessDate = addData.illnessDate.toJSON());
    addData.recoveryDate &&
      (addData.recoveryDate = addData.recoveryDate.toJSON());
    const {
      diseaseName,
      illnessHenhouseNumber,
      illnessChickenTotal,
      deathTotal,
      illnessDate,
      recoveryDate,
      treatmentPlan,
      planResult
    } = addData;

    http
      .post('/feed/diseaseSummaryFarming/save', {
        diseaseName,
        illnessHenhouseNumber,
        illnessChickenTotal,
        deathTotal,
        illnessDate,
        recoveryDate,
        treatmentPlan,
        planResult
      })
      .then(() => {
        http.get('/feed/diseaseSummaryFarming/list/1/10').then((res) => {
          setdataSource(res.data.records);
          form.resetFields();
        });
      })
      .catch((error) => {
        // eslint-disable-next-line no-console
        console.log(error);
      });
  };

  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
    form.resetFields();
    setEdited(null);
  };

  const renderDescription = () => (
    <>
      <p>
        疫病日志是用于记录饲养过程中出现疾病的情况以及所采取的应对措施的记录。在肉鸡管理系统中，疫病日志通常包括以下内容:{' '}
      </p>
      <p>疾病名称：记录出现的疾病名称或症状。</p>
      <p>发病时间：记录疾病发生的时间，以便对病情进行监测。</p>
      <p>发病数量：记录发病的肉鸡数量，以便对病情进行评估。</p>
      <p>应对措施：记录针对疾病所采取的应对措施，例如给药、治疗等。</p>
      <p>处理结果：记录采取应对措施后的疾病处理结果，例如治愈、死亡等。</p>
      <p>备注：记录其他相关信息，例如疾病的传播途径、防控措施等。</p>
    </>
  );

  return (
    <DivWrapper>
      <TipsHeader
        imgSrc={planPicture}
        title="疫病日志"
        description={renderDescription()}
      />
      <ProToolBar buttonGroup={buttonGroup} disableSearchMore={true} />
      <Table
        dataSource={dataSource}
        columns={FormColumsArray}
        scroll={{ x: 1300 }}
      />
      <Modal
        width={'800px'}
        title="新增记录"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
        centered
      >
        <NewForm newref={newref} form={form} />
      </Modal>
    </DivWrapper>
  );
});

export default GetUseManage;
